<template>
  <div class="xiaobu-container" v-closeSelect="'window'">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      class="search-form clearfix"
    >
      <el-form-item
        class="search-field fl five-per-row"
        label="用户名"
        prop="userName"
      >
        <el-input
          v-model.trim="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        class="search-field fl five-per-row"
        label="手机号"
        prop="phoneNumber"
      >
        <el-input
          v-model.trim="queryParams.phoneNumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        class="search-field fl five-per-row"
        label="状态"
        prop="status"
      >
        <el-select-dict
          dictType="STATUS"
          clearable
          placeholder="请选择状态"
          v-model="queryParams.status"
          @dictChange="handleQuery"
        ></el-select-dict>
      </el-form-item>
      <el-form-item
        class="search-field fl five-per-row"
        label="创建时间"
        prop="beginTime"
      >
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          @change="handleQuery"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item class="fr">
        <el-button plain @click="resetQuery">重 置</el-button>
        <el-button type="primary" @click="handleQuery">查 询</el-button>
      </el-form-item>
    </el-form>
    <div class="table-wrap">
      <div class="table-control-box">
        <el-button
          v-hasPermi="['system:user:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          v-hasPermi="['system:user:update']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >编辑</el-button
        >
        <el-button
          v-hasPermi="['system:user:delete']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
          >删除</el-button
        >
        <el-button
          v-hasPermi="['system:user:export']"
          class="fr"
          type="success"
          plain
          :disabled="list.length === 0"
          icon="el-icon-download"
          size="mini"
          @click="openExportWay = true"
          >导出</el-button
        >
        <el-button
          v-hasPermi="['system:user:import']"
          class="fr"
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="showImport = true"
          >导入</el-button
        >
      </div>
      <div class="table-box">
        <el-table
          ref="userTable"
          :class="{ empty: list.length === 0 }"
          empty-text=" "
          v-loading="loading"
          :data="list"
          row-key="userId"
          @selection-change="handleSelectionChange"
          @row-click="clickRow"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
            align="center"
          />
          <el-table-column
            label="用户名"
            prop="userName"
            align="center"
            min-width="120px"
          />
          <el-table-column-dict
            maskType="mobile"
            label="手机号"
            prop="phoneNumber"
            align="center"
            min-width="120px"
          />
          <el-table-column-dict
            dictType="SEX"
            label="用户性别"
            prop="sex"
            align="center"
            min-width="80px"
          />
          <el-table-column
            label="用户角色"
            prop="roleArrStr"
            align="center"
            min-width="168px"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column-dict
            dictType="STATUS"
            dictTypeNode="tag"
            label="用户状态"
            align="center"
            prop="status"
            min-width="100px"
          ></el-table-column-dict>
          <el-table-column-dict
            dateFormat="datetime"
            label="创建时间"
            align="center"
            prop="createTime"
            min-width="200px"
          ></el-table-column-dict>
          <el-table-column-dict
            dateFormat="datetime"
            label="最后更新时间"
            defaultVal="--"
            align="center"
            prop="updateTime"
            min-width="200px"
          ></el-table-column-dict>
          <el-table-column
            v-if="
              hasPermi([
                'system:user:status',
                'system:user:read',
                'system:user:delete',
                'system:user:role',
                'system:user:reset',
              ])
            "
            label="操作"
            align="center"
            width="300px"
            fixed="right"
            class-name="small-padding "
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:user:status']"
                :disabled="scope.row.isSystem === '1'"
                size="mini"
                :type="scope.row.status === '1' ? 'warning' : 'success'"
                @click.native.stop="handleStatusChange(scope.row)"
                >{{ scope.row.status === "1" ? "停用" : "启用" }}</el-button
              >
              <el-button
                v-hasPermi="['system:user:read']"
                size="mini"
                type="primary"
                icon="el-icon-view"
                @click.native.stop="handleUpdate(scope.row)"
                >查看</el-button
              >
              <el-button
                v-hasPermi="['system:user:delete']"
                :disabled="scope.row.isSystem === '1'"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click.native.stop="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                v-hasPermi="['system:user:role']"
                v-if="permissionLength <= 3"
                size="mini"
                @click.native.stop="handleSelectRole(scope.row)"
                >分配角色</el-button
              >
              <el-button
                v-hasPermi="['system:user:reset']"
                v-if="permissionLength <= 3"
                size="mini"
                type="primary"
                plain
                @click.native.stop="handleResetPassword(scope.row)"
                >重置密码</el-button
              >
              <el-dropdown
                v-if="
                  hasPermi(['system:user:role', 'system:user:reset']) &&
                  permissionLength > 3
                "
                @command="(command) => handleCommand(command, scope.row)"
              >
                <span class="el-dropdown-link more" @click.stop >
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-hasPermi="['system:user:role']"
                    command="handleSelectRole"
                    >分配角色</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-hasPermi="['system:user:reset']"
                    command="handleResetPassword"
                    >重置密码</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <el-dialog
      class="export-dialog"
      title="导出方式"
      :visible.sync="openExportWay"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="openExportWay = false"
      width="520px"
    >
      <div class="el-dialog-body-child">
        <p class="export-way">请选择导出方式</p>
        <el-radio-group v-model="exportWay">
          <el-radio label="1">导出全部查询结果</el-radio>
          <el-radio label="2" :disabled="multiple">导出全部选中数据</el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <template>
          <el-button @click="openExportWay = false">关 闭</el-button>
          <el-button type="primary" @click="handleExport">确 定</el-button>
        </template>
      </div>
    </el-dialog>

    <!-- 添加或编辑对话框 -->
    <user-dialog
      ref="userDialog"
      :title="
        baseForm.userId ? (isUpdate ? '编辑用户' : '查看用户') : '新增用户'
      "
      :visible.sync="open"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :isUpdate="isUpdate"
      :baseForm="baseForm"
      @close="open = false"
      @successs="getList"
      width="1024px"
    ></user-dialog>

    <!-- 分配角色 -->
    <select-role
      ref="userRole"
      :title="selectRoleTitle"
      width="1000px"
      :visible.sync="showSelectRole"
      @close="showSelectRole = false"
      @success="handleSelectRoleSuccess"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :userId="selectRoleUserId"
    ></select-role>

    <!-- 批量导入 -->
    <import-dialog
      ref="importDialog"
      title="批量导入"
      :visible.sync="showImport"
      @close="showImport = false"
      :modal-append-to-body="false"
      :append-to-body="true"
      width="800px"
      @success="handleImportSuccess"
      :close-on-click-modal="false"
    ></import-dialog>
  </div>
</template>

<script>
import { userApi } from "@/api"
import SelectRole from "./components/select-role.vue"
import UserDialog from "./components/user-dialog.vue"
import ImportDialog from "./components/import-dialog.vue"
import { downloadFileByBlob } from "@/utils/download"
export default {
  name: "systemUserManage",
  components: {
    SelectRole,
    UserDialog,
    ImportDialog
  },
  data() {
    return {
      showImport: false, // 显示批量导入
      openExportWay: false, // 显示导出方式
      exportWay: "1", // 导出方式
      selectRoleTitle: "", // 分配角色标题
      showSelectRole: false, // 是否显示分配角色
      selectRoleUserId: "", // 选择分配角色时 操作的用户id
      isUpdate: false, // 是否是编辑
      //搜索条件参数
      queryParams: {
        userName: "", // 用户名称
        phoneNumber: "", // 手机号
        status: "", // 状态
        beginTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      list: [],
      selection: [], // 选中的列表数据

      loading: false,
      total: 0,
      roleList: [],

      // 非单个禁用
      single: true,
      // 非多个禁用(0个禁用)
      multiple: true,

      open: false,
      // 表单参数
      baseForm: {
        userName: "", //用户名称
        sex: "", // 性别
        email: "", // 邮箱
        phoneNumber: "", // 手机号
        remark: "" // 备注
      }
    }
  },
  computed: {
    // 五个按钮权限中 有多少个按钮权限
    permissionLength() {
      const permissionList = this.$store.getters.permissionList
      const list = [
        "system:user:status",
        "system:user:read",
        "system:user:delete",
        "system:user:role",
        "system:user:reset"
      ]
      let num = 0
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (permissionList.includes(item)) {
          num++
        }
      }
      return num
    }
  },
  watch: {
    open(val) {
      if (!val) {
        this.isUpdate = false
        this.baseForm = {
          userName: "", //用户名称
          sex: "", // 性别
          email: "", // 邮箱
          phoneNumber: "", // 手机号
          remark: "" // 备注
        }
        this.$refs.userDialog && this.$refs.userDialog.resetForm()
      }
    },
    // 展示分配角色弹框
    showSelectRole(val) {
      if (!val) {
        this.selectRoleUserId = ""
        this.$refs.userRole.clearSelection()
        this.selectRoleTitle = ""
      }
    },
    // 监听show
    showImport(val) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.importDialog.reset()
        })
      }
    }
  },
  created() {
    //获取列表
    this.getList()
  },
  methods: {
    // 角色分配成功
    handleSelectRoleSuccess() {
      this.showSelectRole = false
      this.getList()
    },
    // 更多操作
    handleCommand(command, row) {
      switch (command) {
      case "handleResetPassword":
        this.handleResetPassword(row)
        break
      case "handleSelectRole":
        this.handleSelectRole(row)
        break
      default:
        break
      }
    },
    // 导入成功
    handleImportSuccess() {
      this.showImport = false
      this.getList()
    },
    // 导出
    handleExport() {
      if (this.exportWay === "1") {
        userApi.exportUserByQuery(this.queryParams).then((data) => {
          downloadFileByBlob(data, "用户数据.xlsx", "octet-stream")
          this.$modal.msgSuccess("导出用户数据成功")
          this.openExportWay = false
        })
      } else if (this.exportWay === "2") {
        const ids = []
        for (let i = 0; i < this.selection.length; i++) {
          const item = this.selection[i]
          ids.push(item.userId)
        }
        if (ids.length === 0) {
          this.$modal.msgError("请先勾选导出用户！")
          return
        }
        userApi.exportUserByUserIds({ ids }).then((data) => {
          downloadFileByBlob(data, "用户数据.xlsx", "octet-stream")
          this.$modal.msgSuccess("导出用户数据成功")
          this.exportWay = "1"
          this.openExportWay = false
        })
      }
    },
    // 重置密码
    handleResetPassword(row) {
      let target = event.target
      if (target.nodeName === "SPAN" || target.nodeName === "I") {
        target = event.target.parentNode
      }
      this.$modal
        .confirm(`确认为用户名为【${row.userName}】的用户重置密码？`)
        .then(function() {
          return userApi.resetPassword({ userId: row.userId })
        })
        .then((data) => {
          this.$modal.msgSuccess(data.msg)
        })
        .finally(() => {
          target.blur()
        })
    },
    // 分配角色
    handleSelectRole(row) {
      this.selectRoleTitle = `分配角色（${row.userName}）`
      this.selectRoleUserId = row.userId
      this.showSelectRole = true
    },
    //点击行
    clickRow(row) {
      this.$refs.userTable.toggleRowSelection(row)
    },
    //批量删除用户
    handleBatchDelete() {
      let str = ""
      const ids = []
      for (let i = 0; i < this.selection.length; i++) {
        const item = this.selection[i]
        ids.push(item.userId)
        str += item.userName
        if (i !== this.selection.length - 1) {
          str += ", "
        }
      }

      this.$modal
        .confirm('是否确认删除用户项为"【' + str + '】"的数据项？')
        .then(function() {
          return userApi.batchDeleteItems({ ids })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess("批量删除用户成功")
        })
        .catch(() => {})
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 清空已选项
      this.$refs.userTable.clearSelection()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      userApi
        .getList(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch((err) => {
          if (err?.name === "CanceledError") {
            return
          }
          this.loading = false
        })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
    },

    /** 编辑按钮操作 */
    handleUpdate(row) {
      if (!row.userId) {
        this.isUpdate = true
      }
      const id = row.userId || (this.selection[0] && this.selection[0].userId)
      userApi.getDetailById({ id }).then((data) => {
        this.baseForm = Object.assign(this.baseForm, data)
        this.open = true
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.userId
      this.$modal
        .confirm('是否确认删除用户为"' + row.userName + '"的数据项？')
        .then(function() {
          return userApi.deleteItem({ id })
        })
        .then(() => {
          this.handleQuery()
          // 判断删除的项是否被勾选了
          const flag = this.selection.find((item) => item.userId === id)
          flag && this.$refs.userTable.toggleRowSelection(row, false)
          this.$modal.msgSuccess("删除成功")
        })
    },
    // 状态改变事件
    handleStatusChange(row) {
      userApi
        .changeStatus({
          userId: row.userId,
          status: row.status === "1" ? "0" : "1"
        })
        .then((data) => {
          this.$modal.msgSuccess("改变状态成功")
          this.getList()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.xiaobu-container {
  .tips {
    font-size: 24px;
    margin-left: 12px;
    color: $mainColor;
  }
  .export-dialog {
    ::v-deep .el-dialog {
      .el-dialog__body {
        padding: 24px;
        .export-way {
          height: 40px;
          line-height: 40px;
          font-size: 16px;
          font-weight: bold;
          color: red;
          margin-bottom: 12px;
        }
      }
    }
  }
}
</style>
